package com.aabte.permissionframeworklearn.permission.common;

import com.aabte.permissionframeworklearn.permission.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author Daniel
 */
@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter {

    public static final String START_TIME = "requestStartTime";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // nothing
        String url = request.getRequestURL().toString();
        Map parameterMap = request.getParameterMap();

        request.setAttribute(START_TIME, System.currentTimeMillis());

        log.info("request start. url: {}, params: {}", url, JsonMapper.obj2String(parameterMap));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // nothing
        removeThreadLoadInfo();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // nothing
        String url = request.getRequestURL().toString();
        Map parameterMap = request.getParameterMap();

        Long st = (Long) request.getAttribute(START_TIME);
        Long cost = System.currentTimeMillis() - st;

        log.info("request completed. url: {}, params: {}, cost: {}", url, JsonMapper.obj2String(parameterMap), cost);

        removeThreadLoadInfo();
    }

    public void removeThreadLoadInfo() {
        RequestHolder.remove();
    }
}
